<?php

namespace app\api\controller;

use app\common\model\Post as PostModel;
use app\common\service\FileService;
use app\common\service\wechat\WeChatMnpService;
use app\common\validate\GoodsValidate;
use app\common\model\Goods as GoodsModel;
use think\facade\Db;

class Goods extends BaseApi
{

    protected $dataModel = GoodsModel::class;
    protected array $with = ["userInfo"];

    //发布商品/编辑
    public function release()
    {
        $params = (new GoodsValidate())->post()->goCheck();
        $goodsId = input("id");

        $this->checkAccount();
        $this->wxCheckText($params["title"] . $params["description"]);

        if ($goodsId) {
            $goods = GoodsModel::update($params);
        } else {
            $params["user_id"] = $this->getUserId();
            $goods = GoodsModel::create($params);
        }

        return $this->data($goods);
    }

    /**
     * [帖子详情]
     * @return [json]
     */
    public function detail()
    {

        $id = input("id");
        $userId = $this->getUserIdNoAuth();

        $goodsInfo = GoodsModel::where('id', $id)->with(["userInfo", "topicInfo"])->find();

        $goodsInfo["comment_count"] = Db::name("comment")->where("post_id", $id)->count();

        $goodsInfo["is_follow"] = false;

        if (!empty($userId)) {
            //是否已关注帖子作者
            $isFollow = Db::name("follow")->where(["user_id" => $userId, "follow_uid" => $goodsInfo["user_id"]])->find();
            if ($isFollow) {
                $goodsInfo["is_follow"] = true;
            }
        }

        return $this->data($goodsInfo);
    }

    public function getListByPage()
    {

        $topicId = input("topic_id");

        $list = GoodsModel::where("topic_id", $topicId)->order("id desc")->paginate(10);

        return $this->data($list);
    }

    public function checkGoodsImg()
    {
        $userId = $this->getUserId();
        $user = Db::name("user")->where("id", $userId)->find();

        $goodsId = input("goods_id");

        $imgList = Db::name("goods")->where("id", $goodsId)->value("img_list");
        $imgList = json_decode($imgList);


        foreach ($imgList as $imgSrc) {
            $imgSrc = FileService::getFileUrl($imgSrc);
            $checkInfoJSon = (new WeChatMnpService())->mediaCheckAsync($user["openid"], $imgSrc);
            $checkInfo = json_decode($checkInfoJSon);
            Db::name("media_check")->insert([
                'trace_id' => $checkInfo->trace_id,
                'type' => 2,
                'post_id' => $goodsId,
                'media_src' => $imgSrc,
                'create_time' => time()
            ]);
        }

        return $this->success();
    }
}